﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BGSpaceShooterServer
{
    internal class ThreadSafeRTBUpdater
    {
        private delegate void UpdateListbox(string msg);

        private RichTextBox rtb;



        // This ctor can be called on any thread and passed the reference to the Listbox

        public ThreadSafeRTBUpdater(RichTextBox rtb)
        {
            this.rtb = rtb;

        }



        // Any thread can call this method which indirectly updates the Listbox using Control.Invoke.

        // The call is synchronous, so the calling thread is blocked until the Listbox is update.

        // Consider Control.BeginInvoke for the asynchronous (non-blocking) solution.

        public void UpdateRTB(string newMsg)
        {
            UpdateListbox ulb = new UpdateListbox(this.OnUpdate);

            rtb.Invoke(ulb, new object[] { newMsg });

        }



        // Do not directly call this method.

        // This method is designed to use only as a delegate target that is invoke on the thread that 

        // created the Listbox.

        private void OnUpdate(string msg)
        {

            rtb.AppendText(msg);
            rtb.ScrollToCaret();
        }

    }
}
